<template>
  <div>
    <div class="list" v-show="rightShow === true">
      <div v-if="rightShow === true">
        <div class="close" @click="closeRight()">
          <div class="name">{{ nowRow.nowRow.name }}</div><i class="el-icon-close"></i>
        </div>
        <div @click="com()"><i class="el-icon-chat-dot-square"></i>查看评论</div>
        <div @click="play()"><i class="el-icon-video-play"></i> 播放</div>
        <div @click="like()"><i :class="likeText === '喜欢' ? 'el-icon-star-off' : 'el-icon-star-on'"></i> {{
            likeText
        }}</div>
        <div @click="addList()"><i class="el-icon-folder-add"></i> 添加到歌单</div>
        <div @click="del()" v-if="delShow === true"><i class="el-icon-close"></i>删除</div>
      </div>

    </div>

    <!-- 弹窗 -->
    <el-dialog title="收藏到歌单" :visible.sync="dialogVisible" width="400px" :before-close="handleClose">
      <div v-if="userList !== null">
        <div class="create" @click="create()">
          <div class="createIcon"><i class="el-icon-plus"></i></div>
          <div>新建歌单</div>
        </div>
        <div>

          <div v-for="item in userList.userList" :key="item.id" @click="add(item.id)">
            <div class="create">
              <div class="createIcon">
                <el-image :src="item.coverImgUrl" lazy fit='fill'></el-image>
              </div>

              <div class="desc">
                <div>{{ item.name }}</div>
                <div>{{ item.trackCount }}首</div>
              </div>

            </div>
          </div>

        </div>
      </div>
    </el-dialog>
    <!-- 新建歌单 -->
    <el-dialog title="新建歌单" :visible.sync="dcreateVisible" width="400px" :before-close="handleCloseTwo">
      <el-form :model="createForm" ref="createFormRef" class="demo-ruleForm">
        <el-form-item label="" prop="title">
          <el-input v-model="createForm.title" size="medium"></el-input>
        </el-form-item>
      </el-form>
      <el-checkbox v-model="checked">是否隐私歌单</el-checkbox>
      <el-button type="danger" @click="confirm()">确定</el-button>
    </el-dialog>

  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import debounce from "@/utils/debounce.js";
export default {
  computed: {
    ...mapState(['nowRow', 'cookie', 'userList', 'likeDatas', 'songList']),
  },
  mounted() {
    this.rightShow = false
    if (this.nowRow !== null) {
      this.row = this.nowRow.nowRow.id
    }
    if (
      localStorage.getItem('uid') !== null &&
      localStorage.getItem('cookie') !== null
    ) {
      this.uid = localStorage.getItem('uid');
      this.getCookie = localStorage.getItem('cookie');
      this.likeList();
      this.ifLike()
    }
    if (this.songList !== null) {
      this.delBtn(this.songList.songList)
    }
  },
  watch: {
    nowRow(newVal, oldVal) {
      this.rightShow = true
      this.row = newVal.nowRow.id
    },
    row(newVal, oldVal) {
      if (localStorage.getItem('cookie') !== null) {
        this.likeList();
        this.ifLike()
      }
    },

    songList(newVal, oldVal) {
      this.delBtn(newVal.songList)
    },

    likeDatas(newVal, oldVal) {
      this.likeData = newVal.likeDatas
    },

    likeData(newVal, oldVal) {
      this.ifLike()
    },


    cookie(newVal, oldVal) {
      this.uid = localStorage.getItem('uid');
      this.getCookie = newVal.cookie;
      this.likeList();
      this.ifLike()
    },
  },
  data() {
    return {
      likeText: '喜欢',
      nowSong: [],
      rightShow: false,
      id: '',
      uid: '',
      getCookie: '',
      timer: null,
      likeData: [],
      dialogVisible: false,
      dcreateVisible: false,
      createForm: {
        title: '',
      },
      checked: false,
      privacy: '',
      row: null,
      delShow: false,
    }
  },
  methods: {
    ...mapActions(['saveNowSong', 'clickPlay', 'saveNowSongCount', 'saveUserList', 'savelikeData', 'saveSongList']),
    // 查看歌曲评论
    com() {
      this.$router.push('/songCom')
      window.sessionStorage.setItem('songID', this.nowRow.nowRow.id);
      window.sessionStorage.setItem('songName', this.nowRow.nowRow.name);
    },

    // 播放歌曲
    play() {
      const e = localStorage.getItem('cookie');
      this.$api.musicItem({ ids: this.nowRow.nowRow.id, cookie: localStorage.getItem('cookie') }).then((ret) => {
        ret.songs.map((item, i) => {
          this.nowSong.push(item)
        })
        this.unique()
        this.saveNowSongCount({ nowSongCount: this.nowSong });
      });

      this.$api.songUrl({ cookie: e, id: this.nowRow.nowRow.id, cookie: localStorage.getItem('cookie') }).then((ret) => {
        const title = this.nowRow.nowRow.name;
        const arr = this.nowRow.nowRow.ar.map((item1) => {
          return item1.name;
        });
        const artist = arr.join();
        const pic = this.nowRow.nowRow.al.picUrl;
        this.id = this.nowSong.length

        for (let i = 0; i < this.nowSong.length; i++) {
          if (this.nowSong[i].id === ret.data[0].id) {
            this.id = i
            break
          }
        }

        if (ret.data[0].url !== null) {
          this.saveNowSong({
            id: this.id,
            title,
            artist,
            src: ret.data[0].url,
            pic,
            songId: ret.data[0].id,
          });
          this.$api.scrobble({ id: this.songId, cookie: e, sourceid: this.nowRow.nowRow.al.id, timestamp: this.$utils.timestamp() })
          this.clickPlay({ ifPlay: false });
        } else {
          this.$message.error('该歌曲暂时无法播放!!!');
        }
      });
    },

    delBtn(e) {
      if (this.$route.path === '/songList') {
        for (let i = 0; i < this.userList.userList.length; i++) {
          if (this.userList.userList[i].id === e.id) {
            console.log(this.userList.userList[i].id)
            this.delShow = true
            break
          } else {
            this.delShow = false
          }
        }
      }
    },

    // 喜欢歌曲
    like: debounce(function () {
      if (this.getCookie !== '') {
        if (this.likeText === '已喜欢') {
          this.$api.likeMusic({ id: this.nowRow.nowRow.id, like: false, cookie: this.getCookie, timestamp: this.$utils.timestamp() })
        } else {
          this.$api.likeMusic({ id: this.nowRow.nowRow.id, like: true, cookie: this.getCookie, timestamp: this.$utils.timestamp() })
        }
        if (this.songList !== null) {
          this.$api.getPlayList({ id: this.songList.songList.id, cookie: this.getCookie, timestamp: this.$utils.timestamp() }).then((ret) => {
            if (ret.code === 200) {
              this.saveSongList({ songList: ret.playlist }); // 获取到的明细存入VUEX
            }
          });
        }
        this.likeList()
      } else {
        this.$message.error('需要登录')
      }
    }, 1000),

    ifLike() {
      if (this.likeData.length !== 0) {
        for (let i = 0; i < this.likeData.length; i++) {
          if (this.nowRow !== null) {
            if (this.likeData[i] === this.nowRow.nowRow.id) {
              this.likeText = '已喜欢'
              break
            } else {
              this.likeText = '喜欢'
            }
          }
        }
      }
    },

    // 加入歌单
    addList() {
      if (this.getCookie !== '') {
        this.dialogVisible = true
        this.getList()
      } else {
        this.$message.error('需要登录')
      }
    },

    getList() {
      const playlist = []
      this.$api.userPlayList({ uid: this.uid, timestamp: this.$utils.timestamp() }).then((ret) => {
        for (let i = 0; i < ret.playlist.length; i++) {
          if (ret.playlist[i].creator.userId === parseInt(this.uid)) {
            playlist.push(ret.playlist[i])
          } else {
            continue
          }
        }
        this.saveUserList({ userList: playlist })
      })
    },

    // 喜欢登录用户歌曲的列表
    likeList() {
      this.timer = setTimeout(() => {
        this.likeData = [];
        this.$api
          .likeList({ uid: this.uid, cookie: this.getCookie, timestamp: this.$utils.timestamp() })
          .then((ret) => {
            this.likeData = ret.ids;
            this.savelikeData({ likeDatas: this.likeData })
          });
      }, 500);
    },


    // 创建歌单
    create() {
      this.dcreateVisible = true
      this.createForm.title = this.nowRow.nowRow.name
    },

    // 确认创建
    confirm() {
      this.$refs.createFormRef.validate(async (e) => {
        if (!e) return;
        if (this.checked === true) {
          this.privacy = 10
        }
        this.$api.createList({ name: this.createForm.title, cookie: this.getCookie, timestamp: this.$utils.timestamp(), privacy: this.privacy })
          .then((ret) => {
            if (ret.code === 200) {
              if (this.nowPlaySong !== null) {
                this.$api.addList({ op: 'add', pid: ret.id, tracks: this.nowRow.nowRow.id, cookie: this.getCookie, timestamp: this.$utils.timestamp() })
                  .then((res) => {
                    if (res.status === 200) {
                      this.$message({
                        message: '操作成功',
                        type: 'success',
                      });
                    }
                  })
                this.getList()
              }
              this.dcreateVisible = false
            }
          })
      });
    },

    // 添加歌曲
    add(e) {
      this.$api.addList({ op: 'add', pid: e, tracks: this.nowRow.nowRow.id, cookie: this.getCookie, timestamp: this.$utils.timestamp() })
        .then((res) => {
          if (res.status === 200) {
            this.$message({
              message: '操作成功',
              type: 'success',
            });
          }
        })
      this.getList()
      this.dialogVisible = false
    },

    handleCloseTwo() {
      this.dcreateVisible = false
    },


    handleClose() {
      this.dialogVisible = false
    },

    // 去重
    unique() {
      const hash = {};
      this.nowSong = this.nowSong.reduce((preVal, curVal) => {
        hash[curVal.id] ? '' : hash[curVal.id] = true && preVal.push(curVal);
        return preVal
      }, [])
    },

    closeRight() {
      this.rightShow = false
    },

    // 删除歌曲
    del() {
      this.$api.addList({ op: 'del', pid: this.$utils.getUrlKey('id'), tracks: this.nowRow.nowRow.id, cookie: this.getCookie, timestamp: this.$utils.timestamp() })
        .then((res) => {
          if (res.status === 200) {
            this.$message({
              message: '操作成功',
              type: 'success',
            });
            this.$api.getPlayList({ id: this.$utils.getUrlKey('id'), cookie: this.getCookie, timestamp: this.$utils.timestamp() }).then((ret) => {
              if (ret.code === 200) {
                this.saveSongList({ songList: ret.playlist }); // 获取到的明细存入VUEX
              }
            });
            this.rightShow = false
          }
        })
    },
  },
}
</script>

<style scoped>
.list {
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: fixed;
  width: 200px;
  background: #fafafa;
  font-size: 20px;
  border-radius: 20px;
  box-shadow: 5px 5px 5px 5px rgba(87, 75, 75, 0.2);
  padding-top: 5px;
  padding-left: 5px;
}

.list div {
  cursor: pointer;
  margin-bottom: 5px;
}

.close {
  display: flex;
  justify-content: right;
  margin-bottom: 0 !important;
  margin-right: 10px;
  font-size: 25px;
}

.name {
  font-size: 10px;
  margin-bottom: 0 !important;
  width: 180px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: flex;
  align-items: center;
}

.create {
  display: flex;
  font-size: 20px;
  align-items: center;
  cursor: pointer;
  margin-bottom: 15px;
}

.createIcon {
  width: 40px;
  height: 40px;
  border-radius: 5px;
  display: flex;
  background: #fafafa;
  color: #ec4141;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
}

.createIcon .el-image {
  width: 40px;
  height: 40px;
  margin-right: 0;
}


.desc div:nth-child(2) {
  font-size: 15px;
}

.el-button {
  width: 100%;
}

.el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}

.el-button {
  margin-top: 10px;
}
</style>
